package com.example.yijian.edit.view.popup;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.yijian.R;
import com.example.yijian.edit.background.BackgroundStyleInfo;
import com.example.yijian.edit.background.SpaceItemDecoration;
import com.example.yijian.utils.ScreenUtils;
import com.example.yijian.utils.ToastUtil;
import com.example.yijian.utils.datainfo.ClipInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CanvasStylePopup extends BaseCommonPopupWindow {
    private final static String IMAGE_ASSETS_PATH = "background/image";

    private TextView tvUserAll;
    private RecyclerView mRecyclerView;
    private ImageView ivFinish;

    private boolean userForAll;

    private BackgroundStyleAdapter mBackgroundStyleAdapter;
    private ArrayList<BackgroundStyleInfo> mData;
    private int mOnSelectPosition;
    private OnBackgroundStyleItemClickListener mOnBackgroundStyleItemClickListener;

    public CanvasStylePopup(Context context) {
        super(context);
        setContentView(R.layout.popup_canvas_style);
        initView();
    }

    private void initView() {
        tvUserAll = findViewById(R.id.tv_canvas_use_all);
        mRecyclerView = findViewById(R.id.recyclerView);
        ivFinish = findViewById(R.id.iv_canvas_color_finish);
        ivFinish.setOnClickListener(v -> dismiss());
        tvUserAll.setOnClickListener(v -> {
            userForAll = true;
            if (mOnBackgroundStyleItemClickListener != null) {
                ToastUtil.showToast(getContext(), "已应用到全部片段");
//                mOnBackgroundStyleItemClickListener.onItemClick(true, mColorList.get(mOnSelectPosition));
            }
        });
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mBackgroundStyleAdapter = new BackgroundStyleAdapter();
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mBackgroundStyleAdapter);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(ScreenUtils.dip2px(getContext(), 3), ScreenUtils.dip2px(getContext(), 12)));
    }

    public void setData(ClipInfo clipInfo) {
        mData = new ArrayList<>();
        mData = getBackgroundImageList();
        initRecyclerView();
        int position = 1;
        String nowClipBackgroundValue = clipInfo.getBackgroundValue();
        if (!TextUtils.isEmpty(nowClipBackgroundValue)) {
            position = 0;
        }
        for (int i = 0; i < mData.size(); i++) {
            BackgroundStyleInfo backgroundStyleInfo = mData.get(i);
            if (backgroundStyleInfo == null) {
                continue;
            }
            String filePath = backgroundStyleInfo.getFilePath();
            if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(nowClipBackgroundValue)) {
                break;
            } else if (!TextUtils.isEmpty(filePath) && !TextUtils.isEmpty(nowClipBackgroundValue)
                    && filePath.equals(clipInfo.getBackgroundValue())) {
                position = i;
                break;
            }
        }
        if (position == mOnSelectPosition) {
            return;
        }
        int oldPosition = mOnSelectPosition;
        mOnSelectPosition = position;
        mBackgroundStyleAdapter.notifyItemChanged(oldPosition);
        mBackgroundStyleAdapter.notifyItemChanged(mOnSelectPosition);
    }


    private class BackgroundStyleAdapter extends RecyclerView.Adapter<StyleHolder> {

        @Override
        public StyleHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = null;
            view = LayoutInflater.from(getContext()).inflate(R.layout.item_background_style, null);
            return new StyleHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull StyleHolder styleHolder, int i) {
            final int position = i;
            final BackgroundStyleInfo backgroundStyleInfo = mData.get(i);
            if (backgroundStyleInfo == null) {
                return;
            }
            String filePath = backgroundStyleInfo.getFilePath();
            Glide.with(getContext().getApplicationContext())
                    .asBitmap()
                    .load(TextUtils.isEmpty(filePath) ? backgroundStyleInfo.getIconRcsId() : "file:///android_asset/background/image/" + filePath)
                    .apply(styleHolder.mOptions)
                    .into(styleHolder.mIcon);

            styleHolder.itemView.setOnClickListener(view -> {
                if (mOnBackgroundStyleItemClickListener != null) {
                    mOnBackgroundStyleItemClickListener.onStyleItemClick(userForAll,position, backgroundStyleInfo);
                }
                if (mOnSelectPosition == position) {
                    return;
                }
                notifyItemChanged(mOnSelectPosition);
                mOnSelectPosition = position;
                notifyItemChanged(mOnSelectPosition);
            });

            if (position == 0) {
                styleHolder.mMark.setVisibility(View.GONE);
            } else {
                styleHolder.mMark.setVisibility(mOnSelectPosition == position ? View.VISIBLE : View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }

    }


    private class StyleHolder extends RecyclerView.ViewHolder {

        private RequestOptions mOptions = new RequestOptions();
        private ImageView mIcon;
        private View mMark;

        public StyleHolder(@NonNull View itemView) {
            super(itemView);
            mOptions.skipMemoryCache(false);
            mIcon = itemView.findViewById(R.id.iv_pic);
            mMark = itemView.findViewById(R.id.iv_mark);
        }

    }

    public ArrayList<BackgroundStyleInfo> getBackgroundImageList() {
        AssetManager assets = getContext().getAssets();
        try {
            String[] list = assets.list(IMAGE_ASSETS_PATH);
            if ((list == null) || (list.length <= 0)) {
                return null;
            }
            ArrayList<BackgroundStyleInfo> result = new ArrayList<>();
            BackgroundStyleInfo more = new BackgroundStyleInfo();
            more.setIconRcsId(R.mipmap.icon_background_style_more);
            result.add(more);
            BackgroundStyleInfo nullInfo = new BackgroundStyleInfo();
            nullInfo.setIconRcsId(R.mipmap.icon_background_style_no);
            result.add(nullInfo);
            for (int index = 0; index < list.length; index++) {
                BackgroundStyleInfo canvasStyleInfo = new BackgroundStyleInfo();
                canvasStyleInfo.setFilePath(list[index]);
                result.add(canvasStyleInfo);
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<BackgroundStyleInfo> getData() {
        return mData;
    }

    public BackgroundStyleInfo getSelectData() {
        if (mOnSelectPosition <= 1) {
            return null;
        }
        return mData.get(mOnSelectPosition);

    }


    public void setOnBackgroundStyleItemClickListener(OnBackgroundStyleItemClickListener onBackgroundStyleItemClickListener) {
        this.mOnBackgroundStyleItemClickListener = onBackgroundStyleItemClickListener;
    }

    public interface OnBackgroundStyleItemClickListener {

        /**
         * 样式背景点击回调
         *
         * @param backgroundStyleInfo
         */
        void onStyleItemClick(boolean userAll, int position, BackgroundStyleInfo backgroundStyleInfo);

    }

}
